<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<!-- Scripts -->
<%@ include file="jqgridCommon.jsp"%>
<script src="<%=request.getContextPath()%>/script/textArea.selection.js"></script>
<script type="text/javascript">

	var path="<%=request.getContextPath() %>";
	var pageSize = 100;
	var page = 1;
	var total = 1;
	$(function(){
		//加入textArea的tab格式化
		set_tab_indent_for_textareas();
	});
	 function insertAtCursor(obj, txt) {
         obj.focus();
         //IE support
         if (document.selection) {
             sel = document.selection.createRange();
             sel.text = txt;
         }
         //MOZILLA/NETSCAPE support
         else {
             var startPos = obj.selectionStart;
             var scrollTop = obj.scrollTop;
             var endPos = obj.selectionEnd;
             obj.value = obj.value.substring(0, startPos) + txt + obj.value.substring(endPos, obj.value.length);
             startPos += txt.length;
             obj.setSelectionRange(startPos, startPos);
             obj.scrollTop = scrollTop;
         }
     }
     function getCaretPos(ctrl) {
         var caretPos = 0;
         if (document.selection) {
             // IE Support
             var range = document.selection.createRange();
             // We'll use this as a 'dummy'
             var stored_range = range.duplicate();
             // Select all text
             stored_range.moveToElementText(ctrl);
             // Now move 'dummy' end point to end point of original range
             stored_range.setEndPoint('EndToEnd', range);
             // Now we can calculate start and end points
             ctrl.selectionStart = stored_range.text.length - range.text.length;
             ctrl.selectionEnd = ctrl.selectionStart + range.text.length;
             caretPos = ctrl.selectionStart;
         } else if (ctrl.selectionStart || ctrl.selectionStart == '0')
         // Firefox support
             caretPos = ctrl.selectionStart;
         return (caretPos);
     }

     function getCurrentLineBlanks(obj) {
         var pos = getCaretPos(obj);
         var str = obj.value;
         var i = pos - 1;
         while (i >= 0) {
             if (str.charAt(i) == '\n')
                 break;
             i--;
         }
         i++;
         var blanks = "";
         while (i < str.length) {
             var c = str.charAt(i);
             if (c == ' ' || c == '\t')
                 blanks += c;
             else
                 break;
             i++;
         }
         return blanks;
     }

     function set_tab_indent_for_textareas() {
         /* set all the tab indent for all the text areas */
         $("textarea").each(function() {
             $(this).keydown(function(eve) {
                 if (eve.target != this) return;
                 if (eve.keyCode == 13)
                     last_blanks = getCurrentLineBlanks(this);
                 else if (eve.keyCode == 9) {
                     eve.preventDefault();
                     insertAtCursor(this, "        ");
                     this.returnValue = false;
                 }
             }).keyup(function(eve) {
                 if (eve.target == this && eve.keyCode == 13)
                     insertAtCursor(this, last_blanks);
             });
         });
     }
	
	//加载数据
	function loadDatas(displayNames,models){
		var grid_selector = "#grid-table";
		var pager_selector = "#grid-pager";
	
		jQuery(grid_selector).jqGrid({
			//direction: "rtl",//反方向显示
			postData:getParams(),//参数
			url : path+"/netin/drugNetInDetail.do",
	        datatype : 'json',
	        mtype : 'POST',
	        jsonReader : {  
	        	root:"rows",//array或者List数据 
	        	page: "page",//当前页码
	        	total: "total",//总页数
	        	records: "records",//总记录数
	        	repeatitems: false
	        },  
	        
	        caption: "表信息",
			autowidth: true,
			height: "auto",//高度
			//width:800,
			colNames:displayNames,
			colModel:models, 
	
			rowNum:10,
			rowList:[5,10,20,50,100],
			pager : pager_selector,
			altRows: true,
			//toppager: true,顶端也显示工具条
			
			multiselect: false,//多选
			//multikey: "ctrlKey",
	        multiboxonly: true,
			viewrecords : true,// 显示页面详细信息
	        //合并单元格的函数 
	        gridComplete: function() {
	         },
	
			loadComplete : replaceCss
		});
	}
	//点击查询、上一页、下一页
	function runSql(isClick){
		
		//如果是点击查询按钮，那么page重置为1
		if(isClick){
			page = 1;
		}
		$('#totalRecords').val('');
		$('#totalRecords1').val('');
		$('#grid-table').html('');
		$('#errorMessage').html('');
		
		var getDataUrl = path+"/dataView/getData.do";
		var sqlText = $('#sqlText').val();
		if(sqlText == ''){
			alert('请输入sql');
			return ;
		}
		//如果选中的内容不为空,那么执行先中的sql
		var selectionText = $('#sqlText').selection().text;
		if(selectionText != '' && selectionText != null){
			sqlText = selectionText;
		}
		
		$.ajax({
			url : getDataUrl,
			data : {
				"sql" : sqlText,
				"page" : page
			},
			type : 'post',
			dataType : "json",
			async : false,
			success : function(data) {
				if(data.success){
					var names = data.names;
					var datas = data.datas;
					var totals = data.total;
					var text = [];
					//加载header,即字段信息lable
					text.push('<tr>');
					for(var i=0;i<names.length;i++){
						text.push('<td><strong><a style="text-decoration:none"title="'+
								names[i] +'">'+ names[i] +'</a></strong></td>');
					}
					text.push('</tr>');
					$('#grid-table').append(text);
					//加载数据
					for(var i=0;i<datas.length;i++){
						var dataText = [];
						dataText.push('<tr>');
						for(var j=0;j<names.length;j++){
							var disName = names[j];
							dataText.push('<td>'+ datas[i][disName] +'</td>');
						}
						dataText.push('<tr>');
						$('#grid-table').append(dataText);
					}
					
					//如果记录大于20,则出分页
					if(data.total>20){
						$('#topButton').show();
						$('#underButton').show();
					}else{
						$('#topButton').hide();
						$('#underButton').hide();
					}
					//显示总条数
					$('#totalRecords').html(totals);
					$('#totalRecords1').html(totals);
					//当一直点下一页，大于数据总条数时,page就一直等于最后一页,Math.ceil=整除+1
					if((page*20)>totals){
						page =  Math.ceil(totals/20);
					}
					$('#curPage').html(page);
					$('#curPage1').html(page);
				}else{
					$('#errorMessage').html(data.message);
				}
			}
		});
	}
	
	function prePage(){
		page = page - 1;
		if(page <= 0){
			page = 1;
		}
		runSql(false);
	}
	
	function nextPage(){
		page = page + 1;
		runSql(false);
	}
	
</script>
</head>

<body>
	<div class="wapper">
		<div class="searcher">
			<div><button style="height:30px;" onclick="runSql(true);">查询</button>
			&nbsp;&nbsp;&nbsp;&nbsp;<span>注:1、支持选中sql查询,类似PLSQL。</span>
				&nbsp;<span> 2、sql错误会显示在页面中。<span>
				&nbsp;<span> 3、可以使用tab键进行sql格式化。<span>
				&nbsp;<span> 4、每页显示20条数据,大于20条时会有分页按钮。<span>
			</div><br/>
			<textarea rows="10" style="width: 90%;resize: none;" id="sqlText" ></textarea>
		</div>
		<br>
		<!--内容区域开始-->
		<div>
			<div>
				<div style="margin-left:20px;display: none" id="topButton">
					<button id="pre" onclick="prePage();">上一页</button>
					<span >第<strong id="curPage" style="color: red">1</strong>页</span>
					<button id="next" onclick="nextPage();">下一页</button>
					&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: red">总共
					<strong id="totalRecords" >0</strong>条</span>
				</div>
				<div style="width:100%;margin-left:20px;color:red" id="errorMessage"></div>
				
				<table id="grid-table" border="1" cellspacing="0" 
				style="width:95%;margin-left:20px;background-color: #FFF5EE;"">
					
				</table>
				<br/>
				<div style="margin-left:20px;display: none" id="underButton">
					<button id="pre1" onclick="prePage();">上一页</button>
					<span >第<strong id="curPage1" style="color: red">1</strong>页</span>
					<button id="next1" onclick="nextPage();">下一页</button>
					&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: red">总共
					<strong id="totalRecords1" >0</strong>条</span>
				</div>
			</div>
		</div>
	</div>
</body>
</html>